using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Threading;

namespace Pitoshka.Tools.Helpers
{
	public class DateTimeHelper
	{
		public static DateTime GetWeekStart(DateTime date)
		{
			CultureInfo info = Thread.CurrentThread.CurrentCulture;
			DayOfWeek firstday = info.DateTimeFormat.FirstDayOfWeek;
			DayOfWeek today = info.Calendar.GetDayOfWeek(date);

			int diff = 0;
			if (firstday != DayOfWeek.Sunday && today == DayOfWeek.Sunday)
			{
				diff = 6;
			}
			else
			{
				diff = today - firstday;
			}

			return date.Date.AddDays(-diff);
		}
		public static DateTime GetWeekEnd(DateTime date)
		{
			return GetWeekStart(date.Date).AddDays(-7);
		}
		public static DateTime AddBusinessDays(DateTime date, int days)
		{
			double sign = Convert.ToDouble(Math.Sign(days));
			int unsignedDays = Math.Sign(days) * days;

			for (int i = 0; i < unsignedDays; i++)
			{
				do
				{
					date = date.AddDays(sign);
				}
				while (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday);
			}

			return date;
		}
	}
}
